#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
依赖管理插件
"""

import subprocess
import sys
from pathlib import Path

# 导入统一的环境配置
from env_setup import setup_environment, ENV_CONFIG

# 使用统一的环境配置
ENV_CONFIG = setup_environment()

class DependencyManager:
    """依赖管理插件类"""
    
    def __init__(self):
        self.project_root = ENV_CONFIG['PROJECT_ROOT']
        
    def start(self) -> bool:
        """插件启动方法"""
        print("🔧 依赖管理工具")
        print("=" * 40)
        
        while True:
            print("\n请选择操作:")
            print("1. 📦 安装依赖")
            print("2. 🔍 检查依赖")
            print("3. 🗑️ 清理缓存")
            print("4. ↩️ 返回主菜单")
            
            try:
                choice = input("\n请选择 (1-4): ").strip()
                
                if choice == "1":
                    self.install_dependencies()
                elif choice == "2":
                    self.check_dependencies()
                elif choice == "3":
                    self.clean_cache()
                elif choice == "4":
                    return True
                else:
                    print("❌ 无效选项")
                    
            except KeyboardInterrupt:
                print("\n👋 返回主菜单")
                return True
            except Exception as e:
                print(f"❌ 错误: {e}")
                
        return True
    
    def install_dependencies(self):
        """安装依赖"""
        print("\n📦 开始安装依赖...")
        
        requirements_file = self.project_root / "requirements.txt"
        if not requirements_file.exists():
            print("❌ requirements.txt 文件不存在")
            return
            
        try:
            result = subprocess.run([
                sys.executable, "-m", "pip", "install", "-r", str(requirements_file)
            ], capture_output=True, text=True)
            
            if result.returncode == 0:
                print("✅ 依赖安装成功")
            else:
                print(f"❌ 依赖安装失败: {result.stderr}")
                
        except Exception as e:
            print(f"❌ 安装过程出错: {e}")
    
    def check_dependencies(self):
        """检查依赖"""
        print("\n🔍 检查依赖状态...")
        
        requirements_file = self.project_root / "requirements.txt"
        if not requirements_file.exists():
            print("❌ requirements.txt 文件不存在")
            return
            
        try:
            with open(requirements_file, 'r', encoding='utf-8') as f:
                requirements = [line.strip() for line in f if line.strip() and not line.startswith('#')]
            
            print(f"📋 需要安装 {len(requirements)} 个依赖包:")
            for req in requirements:
                print(f"  - {req}")
                
        except Exception as e:
            print(f"❌ 检查依赖失败: {e}")
    
    def clean_cache(self):
        """清理缓存"""
        print("\n🗑️ 清理pip缓存...")
        
        try:
            result = subprocess.run([
                sys.executable, "-m", "pip", "cache", "purge"
            ], capture_output=True, text=True)
            
            if result.returncode == 0:
                print("✅ 缓存清理成功")
            else:
                print(f"❌ 缓存清理失败: {result.stderr}")
                
        except Exception as e:
            print(f"❌ 清理缓存出错: {e}") 